//
//  LMProductsController.m
//  EPA
//
//  Created by lanou3g on 16/4/20.
//  Copyright © 2016年 liman. All rights reserved.
//

#import "LMProductsController.h"
#import "LMProductModel.h"
#import "LMProductsCell.h"
#import "LMNetWorkRequestManager.h"
#import "LORefresh.h"
#import "LMBuyViewController.h"
@interface LMProductsController ()
///良品数组
@property (nonatomic, strong)NSMutableArray *products;
///刷新起始位置
@property (nonatomic, strong) NSString *start;
///Header属性
@property (nonatomic , strong) LORefresh *headerRefresh;
@end

@implementation LMProductsController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.products = [NSMutableArray array];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.start = @"0";
    [self loadDataFromStart:self.start];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"LMProductsCell" bundle:nil] forCellReuseIdentifier:@"LMProductsCell"];
    
    [self addRefresh];

}


#pragma mark - 上下刷新机制
-(void)addRefresh{
  __weak typeof(self) weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderGif refreshingBlock:^{
        [weakSelf.products removeAllObjects];
        [weakSelf.tableView reloadData];
        [weakSelf loadDataFromStart:@"0"];
    }];
    
    self.headerRefresh = [self.tableView gifHeader];
    [self.headerRefresh setGifName:@"wangnima"];
    
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        NSInteger count = weakSelf.products.count;
        weakSelf.start = [NSString stringWithFormat:@"%ld",count];
        [weakSelf loadDataFromStart:weakSelf.start];
    }];
}
-(void)dealloc{
    [self.tableView removeObserver:[self.tableView gifHeader] forKeyPath:@"contentOffset"];    
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentSize"];
}

#pragma mark - 解析数据
- (void)loadDataFromStart:(NSString *)strat{
    NSDictionary *params  = [NSDictionary dictionary];
    if ([UserInfoManager shareManager].auth != nil) {
        params = @{@"start":strat,@"client":@"1",@"deviceid":@"63A94D37-33F9-40FF-9EBB-481182338873",@"limit":@10,@"auth":[UserInfoManager shareManager].auth,@"version":@"3.0.2"};
    }else{
         params = @{@"start":strat,@"client":@"1",@"deviceid":@"63A94D37-33F9-40FF-9EBB-481182338873",@"limit":@10,@"auth":@"",@"version":@"3.0.2"};
    }
    [LMNetWorkRequestManager requestURL:[NSURL URLWithString:SHOPLIST_URL] Method:LM_POST Params:params Result:^(NSData *data, NSURLResponse *response, NSError *error) {
//        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
        if (data) {
             NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dataDict = jsonDict[@"data"];
        
            for (NSDictionary *item in dataDict[@"list"]) {
                LMProductModel *model = [[LMProductModel alloc]init];
                [model setValuesForKeysWithDictionary:item];
                [self.products addObject:model];
                
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
              [self.tableView reloadData];
                [[self.tableView gifHeader] endRefreshing];
                [[self.tableView defaultFooter]endRefreshing];
                
            });
            
        }
    }];
    
    
    
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.products.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LMProductsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LMProductsCell" forIndexPath:indexPath];
    cell.model = self.products[indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    LMBuyViewController *buyVC= [[LMBuyViewController alloc]init];
    LMProductModel *model =self.products[indexPath.row];
    buyVC.buyUrl =model.buyurl;
    
    [self.navigationController pushViewController:buyVC animated:YES];
   
   
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
